package pay

import (
	"OnlineRetailers/controllers/OpenId"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	PAY "OnlineRetailers/models/pay"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type PostPay struct {
	beego.Controller
}

func (c *PostPay) PostPay() {

	defer func() {
		c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/pay/PostPay"
	var err error
	res := &PAY.GetPay{}
	order := &User.Order{}
	log := &error2.Log{}
	//mes := &error2.Mes{}

	//o := orm.NewOrm()

	err = json.Unmarshal([]byte(c.GetString("order")), order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//fmt.Println(order.User)
	openidTemp := c.Ctx.Request.Header["Openid"]

	if len(openidTemp) == 0 {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("openidNull"), addr, "openidNull")
		return
	}
	openid := openidTemp[0]
	if openid == "" {
		c.Data["json"] = errorDeal.ErrMess(log, "400", fmt.Errorf("openidNull"), addr, "openidNull")
		return
	}

	err = OpenId.CheckOpenId(openid)
	//fmt.Println(ses.Admin)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//_, err = o.Insert(order)

	err = checkOrder(order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	if order.OrderId == "" {
		err = postOrder(order)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	err, resq := pay(openid, order)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//err = New(order.OrderId, order)
	//if err != nil {
	//	c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
	//	return
	//}
	order.State = 2
	err = UpData(order, openid)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	res.OrderId = order.OrderId
	res.Response = resq
	res.Mes = "success"
	res.Code = "200"
	c.Data["json"] = res
}

func UpData(order *User.Order, openid string) (err error) {

	o := orm.NewOrm()
	sql := "update `order` set state = ? where order_id = ? "
	exec, err := o.Raw(sql, order.State, order.OrderId).Exec()
	if err != nil {
		return
	}
	num, err := exec.RowsAffected()
	if err != nil {
		return
	} else if num == 0 {
		err = fmt.Errorf("失败NUM==0")
		return
	}

	if order.State == 2 && order.Coupon.CouponId != "0" {
		err = UsedCoupon(order.Coupon.CouponId, openid)
		if err != nil {
			return
		}
	}
	return nil
}
